package com.efounder.chat.activity;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.widget.SwitchCompat;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.efounder.chat.R;
import com.efounder.chat.db.WeChatDBManager;
import com.efounder.chat.http.GetHttpUtil;
import com.efounder.chat.model.ChatListItem;
import com.efounder.chat.model.MessageEvent;
import com.efounder.chat.struct.StructFactory;
import com.efounder.chat.utils.LXGlideImageLoader;
import com.efounder.constant.EnvironmentVariable;
import com.efounder.frame.activity.EFAppAccountMainActivity;
import com.efounder.frame.manager.AppAccountResDownloader;
import com.efounder.frame.utils.EFAppAccountUtils;
import com.efounder.message.manager.JFMessageManager;
import com.efounder.mobilecomps.contacts.User;
import com.efounder.util.LoadingDataUtilBlack;
import com.efounder.util.ToastUtil;
import com.efounder.utils.CommonUtils;
import com.efounder.utils.ResStringUtil;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;

import java.util.LinkedHashMap;
import java.util.Map;

import static com.efounder.frame.utils.Constants.CHAT_PASSWORD;
import static com.efounder.frame.utils.Constants.CHAT_USER_ID;


/**
 * @author Administrator-lch
 * 用户详情信息
 */
public class PublicNumerInfoActivity extends BaseActivity implements OnClickListener {

    boolean is_friend = false;
    ImageView detailMoreView;//右上角设置按钮

    // 发送按钮
    Button btn_sendmsg;
    // 头像区域
    ImageView iv_avata;
    // 性别
    ImageView iv_sex;
    // 用户名
    TextView tv_name;
    LinearLayout middleArea;

    ImageView iv_switch_open_islocationable;
    ImageView iv_switch_close_islocationable;

    private String pubNumName;//公众号名称
    private int pubNumId;//公众号id
    private User user;
    private ProgressDialog progressDialog;
    private String url;

    private boolean isAttention = true;///是否已经关注


    // 状态变化
    private SwitchCompat switchTop;// 置顶聊天
    private SwitchCompat switchNotification;// 免打扰

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_publicnuminfo);

        if (getIntent().hasExtra("user")) {
            user = (User) getIntent().getExtras().get(
                    "user");
            pubNumId = user.getId();
            pubNumName = user.getNickName();
            initView();
            initAvatar();
            initData();
        } else if (getIntent().hasExtra("id")) {
            pubNumId = getIntent().getIntExtra("id", 1);
            user = WeChatDBManager.getInstance().getOneUserById(pubNumId);

            User user1 = WeChatDBManager.getInstance().getOneOfficialNumber(pubNumId);
            if (user1 == null) {
                isAttention = false;
            }
            GetHttpUtil.getUserInfo(pubNumId, PublicNumerInfoActivity.this, new GetHttpUtil.GetUserListener() {
                @Override
                public void onGetUserSuccess(User user1) {
                    user = WeChatDBManager.getInstance().getOneUserById(user1.getId());
                    initView();
                    initAvatar();
                    initData();
                }

                @Override
                public void onGetUserFail() {

                }
            });
            user.setType(User.PUBLICFRIEND);
            pubNumName = user.getNickName();
            if (String.valueOf(pubNumId).equals(user.getNickName())) {
                progressDialog = new ProgressDialog(this);
                progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
                progressDialog.setMessage(ResStringUtil.getString(R.string.common_text_please_wait));

            } else {
                initView();
                initAvatar();
                initData();
            }
        }


    }

    private void initData() {
        User user1 = new User();

        user1.setNickName(pubNumName);
        user1.setId(pubNumId);

        Map<String, String> map = new LinkedHashMap<String, String>();

//        map.put("功能介绍：", "发布新闻公告");
////        map.put("所属部门：", "网络运维部");
//        map.put("客服电话：", "0531-88872656");
        map.put(ResStringUtil.getString(R.string.chat_function_introduce), "");
//        map.put("所属部门：", "网络运维部");
        map.put(ResStringUtil.getString(R.string.chat_customer_phone), "");

        user1.setRemarkmap(map);

        this.setcontent(user1);

    }


    private void initView() {
        TextView tvTitle = (TextView) findViewById(R.id.tv_title);
        tvTitle.setText(R.string.chat_detail_info);
        btn_sendmsg = (Button) this.findViewById(R.id.btn_sendmsg);
        iv_avata = (ImageView) this.findViewById(R.id.iv_avatar);
        iv_sex = (ImageView) this.findViewById(R.id.iv_sex);
        tv_name = (TextView) this.findViewById(R.id.tv_name);
        ImageView iv_erweima = (ImageView) this.findViewById(R.id.iv_erweima);
        detailMoreView = (ImageView) this.findViewById(R.id.iv_detail);
        detailMoreView.setVisibility(View.VISIBLE);
        iv_erweima.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {

                Intent intent = new Intent(PublicNumerInfoActivity.this, CreateUserQRCode.class);

                Bundle bundle = new Bundle();
                bundle.putString("type", "addPublicNum");
                bundle.putString("id", String.valueOf(pubNumId));
                bundle.putString("avatar", user.getAvatar());
                bundle.putString("nickname", pubNumName);

                intent.putExtras(bundle);
                startActivity(intent);

            }
        });

        switchTop = (SwitchCompat) findViewById(R.id.switch_top);
        switchNotification = (SwitchCompat) findViewById(R.id.switch_notification);
        switchNotification.setChecked(!user.getIsBother());
        switchTop.setChecked(user.getIsTop());
        switchNotification.setOnClickListener(this);
        switchTop.setOnClickListener(this);

        //如果没有关注应用号，不显示置顶，接受消息的按钮
        if (!isAttention) {
            RelativeLayout rl_switch_notification = (RelativeLayout) findViewById(R.id.rl_switch_notification);
            rl_switch_notification.setVisibility(View.GONE);
            RelativeLayout rl_switch_sound = (RelativeLayout) findViewById(R.id.rl_switch_sound);
            rl_switch_sound.setVisibility(View.GONE);
        }
        iv_switch_open_islocationable = (ImageView) this
                .findViewById(R.id.iv_switch_open_islocationable);
        iv_switch_close_islocationable = (ImageView) this
                .findViewById(R.id.iv_switch_close_islocationable);

        iv_switch_open_islocationable.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                iv_switch_close_islocationable.setVisibility(View.VISIBLE);
                iv_switch_open_islocationable.setVisibility(View.GONE);

            }
        });

        iv_switch_close_islocationable
                .setOnClickListener(new OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        iv_switch_open_islocationable
                                .setVisibility(View.VISIBLE);
                        iv_switch_close_islocationable.setVisibility(View.GONE);
                    }
                });

        middleArea = (LinearLayout) this.findViewById(R.id.middle_remark);

        btn_sendmsg.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                if (getIntent().hasExtra("finish")) {
                    finish();
                    return;
                }


                if (!getIntent().hasExtra("publicchatfragment")) {
                    //如果不是publicchatfragment跳转而来，否则直接结束该activity
                    Intent intent = null;
//                    if (user.getId() == 2307){//代记账应用号-2307
//                        intent = new Intent(PublicNumerInfoActivity.this, EFAppAccountDJZMainActivity.class);
//                    }else {
//                        intent = new Intent(PublicNumerInfoActivity.this, EFAppAccountMainActivity.class);
//                    }
                    intent = new Intent(PublicNumerInfoActivity.this, EFAppAccountMainActivity.class);
                    intent.putExtra("id", user.getId());
                    intent.putExtra("nickName", user.getNickName());
                    startActivity(intent);
                }
                finish();
            }

        });

        detailMoreView.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                showPopWindow(detailMoreView);
            }
        });

    }

    @Override
    public void onClick(View v) {
        final int id = v.getId();
        if (id == R.id.switch_notification) {

            user.setIsBother(!switchNotification.isChecked());
            WeChatDBManager.getInstance().insertOrUpdateUser(user);
        } else if (id == R.id.switch_top) {// 消息置顶
            user.setIsTop(switchTop.isChecked());
            WeChatDBManager.getInstance().insertOrUpdateUser(user);
        }

    }

    public void initAvatar() {
        if (user != null) {
            LXGlideImageLoader.getInstance().showRoundUserAvatar(this, iv_avata, user.getAvatar()
                    , LXGlideImageLoader.DEFATLT_AVATAR_RADIUS_10);
        } else {
            LXGlideImageLoader.getInstance().showRoundUserAvatar(this, iv_avata, R.drawable.default_user_avatar
                    , LXGlideImageLoader.DEFATLT_AVATAR_RADIUS_10);
        }
    }

    /**
     * 设置内容
     *
     * @param user
     */
    private void setcontent(User user) {
        middleArea.removeAllViews();
        // 设置用户名
        tv_name.setText(user.getNickName());
        // 设置描述区域
        Map<String, String> remarkMap = user.getRemarkmap();

        LayoutInflater inflater = LayoutInflater.from(this);
        for (String key : remarkMap.keySet()) {
            System.out.println("key= " + key + " and value= "
                    + remarkMap.get(key));
            ViewGroup userinfo_merge = (ViewGroup) inflater.inflate(
                    R.layout.userinfo_merge, null);
            TextView merge_key = (TextView) userinfo_merge
                    .findViewById(R.id.merge_key);
            merge_key.setText(key);

            TextView merge_value = (TextView) userinfo_merge
                    .findViewById(R.id.merge_value);
            merge_value.setText(remarkMap.get(key));

            LinearLayout.LayoutParams lp = new LayoutParams(
                    LayoutParams.MATCH_PARENT, CommonUtils.dip2px(this, 48));
            middleArea.addView(userinfo_merge, lp);
        }

    }

    @Override
    protected void onStop() {
        super.onStop();
        notifyChange(user);
    }

    private void notifyChange(User user) {

        ChatListItem chatListItem = WeChatDBManager.getInstance().getChatListItem(user.getId(), StructFactory.TO_USER_TYPE_PERSONAL);
        if (chatListItem == null) {
            return;
        }
        EventBus.getDefault().post(new MessageEvent(chatListItem, MessageEvent.UPDATE));
    }

    @Override
    public void back(View view) {
        finish();
    }

    public void showPopWindow(View view) {


        final PopupWindow popupWindow = new PopupWindow(this);

        // 设置SelectPicPopupWindow弹出窗体的宽
        popupWindow.setWidth(ViewGroup.LayoutParams.WRAP_CONTENT);
        // 设置SelectPicPopupWindow弹出窗体的高
        popupWindow.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
        // 设置SelectPicPopupWindow弹出窗体可点击
        popupWindow.setFocusable(true);
        popupWindow.setOutsideTouchable(true);
        // 刷新状态
        popupWindow.update();
        // 实例化一个ColorDrawable颜色为半透明
        ColorDrawable dw = new ColorDrawable(0000000000);
        // 点back键和其他地方使其消失,设置了这个才能触发OnDismisslistener ，设置其他控件变化等操作
        popupWindow.setBackgroundDrawable(dw);

        // 设置SelectPicPopupWindow弹出窗体动画效果
        popupWindow.setAnimationStyle(R.style.AnimationPreview);
        View conentView;
        LayoutInflater inflater = (LayoutInflater) this
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        conentView = inflater.inflate(R.layout.popupwindow_beizhu, null);
        RelativeLayout useless = (RelativeLayout) conentView.findViewById(R.id.setbeizhi);//没用到的
        TextView textView = (TextView) conentView.findViewById(R.id.text1);
        textView.setText(R.string.chat_check_up);
        RelativeLayout deleteRe = (RelativeLayout) conentView.findViewById(R.id.deletefriend);//没用到的
        useless.setVisibility(View.VISIBLE);
        TextView deleteTv = (TextView) conentView.findViewById(R.id.text2);
        deleteTv.setText(R.string.chat_cancel_follow);
        // 设置SelectPicPopupWindow的View
        popupWindow.setContentView(conentView);
        if (!isAttention) {
            deleteRe.setVisibility(View.GONE);
            textView.setText(R.string.chat_follow);
            useless.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    popupWindow.dismiss();
                    focusPublicNumber();
                }
            });
            popupWindow.showAsDropDown(view, 0, 0);
            return;
        }

        useless.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                popupWindow.dismiss();
                downResource();
            }
        });

        deleteRe.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                popupWindow.dismiss();
                new AlertDialog.Builder(PublicNumerInfoActivity.this).
                        setMessage(ResStringUtil.getString(R.string.chat_sure_cancel_follow)).setTitle(R.string.common_text_hint).
                        setNegativeButton(R.string.common_text_cancel, null).
                        setPositiveButton(R.string.common_text_confirm, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                try {
                                    GetHttpUtil.cannalFocusPublicNumber(PublicNumerInfoActivity
                                                    .this,
                                            user.getId(), new GetHttpUtil.FocusPublicCallBack() {
                                                @Override
                                                public void focusPublicSuccess(boolean isSuccess) {
                                                    if (isSuccess) {
                                                        clearBadgem(user.getId(), (byte) 0);
                                                        WeChatDBManager.getInstance().cannalFocusOfficialNumber
                                                                (user.getId());

                                                        //跳转到首页
                                                        try {
                                                            String className = getResources().getString(R.string.from_group_backto_first);
                                                            Class clazz = Class.forName(className);
                                                            Intent myIntent = new Intent
                                                                    (PublicNumerInfoActivity
                                                                            .this, clazz);
                                                            startActivity(myIntent);
                                                        } catch (ClassNotFoundException e) {
                                                            e.printStackTrace();
                                                        }

                                                        ToastUtil.showToast
                                                                (PublicNumerInfoActivity.this,
                                                                        R.string.chat_cancel_follow_success);
                                                        PublicNumerInfoActivity.this.finish();
                                                    } else {
                                                        ToastUtil.showToast
                                                                (PublicNumerInfoActivity.this,
                                                                        R.string.chat_cancel_follow_fail);

                                                    }
                                                }
                                            });
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }

                                dialogInterface.dismiss();
                            }
                        }).show();

            }
        });

        popupWindow.showAsDropDown(view, 0, 0);
    }


    /**
     * 关注应用号
     */
    private void focusPublicNumber() {
        LoadingDataUtilBlack.show(PublicNumerInfoActivity.this, ResStringUtil.getString(R.string.chat_following));
        try {
            GetHttpUtil.focusPublicNumber(PublicNumerInfoActivity.this,
                    EnvironmentVariable.getProperty(CHAT_USER_ID),
                    EnvironmentVariable.getProperty(CHAT_PASSWORD),
                    user.getId(),
                    new GetHttpUtil.FocusPublicCallBack() {
                        @Override
                        public void focusPublicSuccess(boolean isSuccess) {
                            if (isSuccess) {
                                LoadingDataUtilBlack.dismiss();
                                user.setType(User.PUBLICFRIEND);
                                user.setIsBother(false);
                                user.setLoginUserId(Integer.parseInt(EnvironmentVariable.getProperty(CHAT_USER_ID)));
                                 WeChatDBManager.getInstance()
                                        //  .insertOfficialNumber(user);
                                        .insertUserTable(user);

                                if (user.getGroupUserType() == 0) {
                                    ToastUtil.showToast(PublicNumerInfoActivity.this, R.string.chat_follow_public_success);

                                } else {

                                    showAlertDialog();//展示需要申请的提示
                                }

                            } else {
                                LoadingDataUtilBlack.dismiss();
                                ToastUtil.showToast(PublicNumerInfoActivity.this,
                                        R.string.chat_follow_public_fail);
                            }
                        }
                    });
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private void showAlertDialog() {
        new AlertDialog.Builder(PublicNumerInfoActivity.this).
                setMessage(ResStringUtil.getString(R.string.chat_send_request_success)).setTitle(R.string.common_text_hint)
                .setPositiveButton(R.string.common_text_confirm, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        PublicNumerInfoActivity.this.finish();
                        dialogInterface.dismiss();
                    }
                }).show();
    }

    private void clearBadgem(int id, byte chatType) {

        //清除当前聊天的角标
        ChatListItem chatListItem = WeChatDBManager.getInstance().getChatListItem(id, chatType);

        JFMessageManager.getInstance().unreadZero(id, chatType);
        int unReadCount = JFMessageManager.getInstance().getUnReadCount(id, chatType);
        if (unReadCount == 0) {
            unReadCount = -1;
        }

        if (chatListItem != null) {
            chatListItem.setBadgernum(unReadCount);
            WeChatDBManager.getInstance().deleteChatListiItem(chatListItem);
            EventBus.getDefault().post(new MessageEvent(chatListItem, MessageEvent.DELETE));

            // ChatListItemUtil.updateUnreadCount(unReadCount, 0);
        }


    }


    private void downResource() {
        ///TODO 下载之前，先删除应用号文件夹
        int appAccountID = pubNumId;
        EFAppAccountUtils.deleteAppAccountRoot(appAccountID);
        final AppAccountResDownloader appAccountResDownloader = new AppAccountResDownloader(this, appAccountID);
        appAccountResDownloader.downloadResource(new AppAccountResDownloader.DownloadAppAccountResourceListener() {
            @Override
            public void onResourceDownloadSuccess() {
                AppAccountResDownloader.markUpdateOver(EFAppAccountUtils.getAppAccountID());
                appAccountResDownloader.sendBroadcast();

                PublicNumerInfoActivity.this.finish();

                Intent intent = null;
//                if (user.getId() == 2307){//代记账应用号-2307
//                    intent = new Intent(PublicNumerInfoActivity.this, EFAppAccountDJZMainActivity.class);
//                }else {
//                    intent = new Intent(PublicNumerInfoActivity.this, EFAppAccountMainActivity.class);
//                }
                intent = new Intent(PublicNumerInfoActivity.this, EFAppAccountMainActivity.class);
                intent.putExtra("id", user.getId());
                intent.putExtra("nickName", user.getNickName());
                startActivity(intent);
            }
        });

    }


}
